package com.atguigu.gmall.order.receiver;


import com.atguigu.gmall.common.config.constant.MqCons;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    //接收延迟消息 为了取消订单
    @RabbitListener(queues = MqCons.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId,Message message, Channel channel){
        //获取订单ID
       // String orderId = new String(message.getBody());
        System.out.println("取消订单：" + orderId);
        try {
            orderService.cancelOrder(orderId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    //更新订单支付状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqCons.QUEUE_PAYMENT_PAY),
            exchange = @Exchange(value = MqCons.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = MqCons.ROUTING_PAYMENT_PAY
    ))
    public void paySuccess(Message message,Channel channel,Long orderId){
        try {
            OrderInfo orderInfo = null;
            if(null != orderId){
                orderInfo = orderService.getOrderInfo(orderId);
            }
            if(orderInfo != null && orderInfo.getOrderStatus().equals(OrderStatus.UNPAID.name())){
                //更新订单时
                orderService.updateOrderStatus(orderInfo);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
